package com.zmc.order.infrastructure.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zmc.common.utils.StringUtils;
import com.zmc.common.utils.token.AuthTokenService;
import com.zmc.order.infrastructure.bean.query.PaymentInfoQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Objects;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zmc.common.utils.PageUtils;

import com.zmc.order.infrastructure.dao.PaymentInfoDao;
import com.zmc.order.infrastructure.entity.PaymentInfoEntity;
import com.zmc.order.infrastructure.service.PaymentInfoService;


/**
 * @author zmc
 */
@Service("paymentInfoService")
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoDao, PaymentInfoEntity> implements PaymentInfoService {

    @Autowired
    private AuthTokenService authTokenService;

    @Override
    public PageUtils queryPage(PaymentInfoQuery query) {
        return new PageUtils(baseMapper.selectPage(new Page<>(query.getPageNum(), query.getPageSize()), getWrapper(query)));
    }

    @Override
    public PaymentInfoEntity getByOrderSn(String orderSn) {
        LambdaQueryWrapper<PaymentInfoEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PaymentInfoEntity::getMerchantId, authTokenService.getMemberInfo().getMemberId())
                .eq(PaymentInfoEntity::getOrderSn, orderSn)
                .last(" limit 1");
        return getOne(wrapper);
    }

    @Override
    public List<PaymentInfoEntity> selectList(PaymentInfoQuery query) {
        return list(getWrapper(query));
    }

    private LambdaQueryWrapper<PaymentInfoEntity> getWrapper(PaymentInfoQuery query) {
        LambdaQueryWrapper<PaymentInfoEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PaymentInfoEntity::getMerchantId, authTokenService.getMemberInfo().getMemberId())
                .eq(StringUtils.isNotEmpty(query.getOrderSn()), PaymentInfoEntity::getOrderSn, query.getOrderSn())
                .eq(!Objects.isNull(query.getStatus()), PaymentInfoEntity::getPaymentStatus, query.getStatus())
                .orderByDesc(PaymentInfoEntity::getCreateTime);
        return wrapper;
    }

}